package cn.iocoder.yudao.module.book.service.community;

import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.book.controller.app.community.vo.PostCommentCreateReqVO;
import cn.iocoder.yudao.module.book.controller.app.community.vo.PostCommentRespVO;
import cn.iocoder.yudao.module.book.dal.dataobject.community.PostCommentsDO;
import cn.iocoder.yudao.module.book.dal.dataobject.community.PostLikesDO;
import cn.iocoder.yudao.module.book.dal.mysql.community.CommunityPostsMapper;
import cn.iocoder.yudao.module.book.dal.mysql.community.PostCommentsMapper;
import cn.iocoder.yudao.module.book.dal.mysql.community.PostLikesMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;

/**
 * 动态评论 Service 实现类
 *
 * @author system
 */
@Service
public class PostCommentsServiceImpl implements PostCommentsService {

    @Resource
    private PostCommentsMapper postCommentsMapper;

    @Resource
    private PostLikesMapper postLikesMapper;

    @Resource
    private CommunityPostsMapper communityPostsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createComment(Long postId, @Valid PostCommentCreateReqVO createReqVO, Integer userId) {
        // 1. 创建评论
        PostCommentsDO comment = PostCommentsDO.builder()
                .postId(postId)
                .userId(userId)
                .parentId(createReqVO.getParentId())
                .replyToUserId(createReqVO.getReplyToUserId())
                .content(createReqVO.getContent())
                .likesCount(0)
                .status(1)
                .build();
        postCommentsMapper.insert(comment);

        // 2. 更新动态评论数
        communityPostsMapper.updateCommentsCount(postId, 1);

        return comment.getCommentId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteComment(Long commentId, Integer userId) {
        // 1. 验证评论是否存在且属于当前用户
        PostCommentsDO comment = postCommentsMapper.selectById(commentId);
        if (comment == null) {
            throw ServiceExceptionUtil.exception(BAD_REQUEST, "评论不存在");
        }
        if (!comment.getUserId().equals(userId)) {
            throw ServiceExceptionUtil.exception(BAD_REQUEST, "无权限删除此评论");
        }

        // 2. 删除评论（软删除）
        comment.setStatus(-1);
        postCommentsMapper.updateById(comment);

        // 3. 更新动态评论数
        communityPostsMapper.updateCommentsCount(comment.getPostId(), -1);
    }

    @Override
    public PageResult<PostCommentRespVO> getCommentsPage(Long postId, Integer page, Integer pageSize, Integer userId) {
        // 1. 查询评论列表
        PageResult<PostCommentsDO> pageResult = postCommentsMapper.selectCommentsPage(postId, page, pageSize);

        // 2. 转换为VO
        List<PostCommentRespVO> respVOs = pageResult.getList().stream()
                .map(comment -> convertToRespVO(comment, userId))
                .collect(Collectors.toList());

        return new PageResult<>(respVOs, pageResult.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer likeComment(Long commentId, Integer userId) {
        // 1. 检查是否已点赞
        PostLikesDO existingLike = postLikesMapper.selectCommentLike(commentId, userId);
        if (existingLike != null && existingLike.getStatus() == 1) {
            throw ServiceExceptionUtil.exception(BAD_REQUEST, "已经点赞过了");
        }

        // 2. 创建或更新点赞记录
        if (existingLike == null) {
            PostLikesDO like = PostLikesDO.builder()
                    .commentId(commentId)
                    .userId(userId)
                    .likeType(2)
                    .status(1)
                    .build();
            postLikesMapper.insert(like);
        } else {
            existingLike.setStatus(1);
            postLikesMapper.updateById(existingLike);
        }

        // 3. 更新评论点赞数
        postCommentsMapper.updateLikesCount(commentId, 1);

        // 4. 返回最新点赞数
        PostCommentsDO comment = postCommentsMapper.selectById(commentId);
        return comment.getLikesCount();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer unlikeComment(Long commentId, Integer userId) {
        // 1. 检查点赞记录
        PostLikesDO existingLike = postLikesMapper.selectCommentLike(commentId, userId);
        if (existingLike == null || existingLike.getStatus() == 0) {
            throw ServiceExceptionUtil.exception(BAD_REQUEST, "还未点赞");
        }

        // 2. 取消点赞
        existingLike.setStatus(0);
        postLikesMapper.updateById(existingLike);

        // 3. 更新评论点赞数
        postCommentsMapper.updateLikesCount(commentId, -1);

        // 4. 返回最新点赞数
        PostCommentsDO comment = postCommentsMapper.selectById(commentId);
        return comment.getLikesCount();
    }

    /**
     * 转换为响应VO
     */
    private PostCommentRespVO convertToRespVO(PostCommentsDO comment, Integer userId) {
        PostCommentRespVO respVO = new PostCommentRespVO();
        respVO.setCommentId(comment.getCommentId());
        respVO.setUserId(comment.getUserId());

        // 设置用户信息（这里简化处理，实际项目中应该查询用户表）
        respVO.setUsername("用户" + comment.getUserId());
        respVO.setAvatar("https://example.com/avatar/default.jpg");

        respVO.setContent(comment.getContent());
        respVO.setLikesCount(comment.getLikesCount());
        respVO.setParentId(comment.getParentId());
        respVO.setReplyToUserId(comment.getReplyToUserId());

        // 设置回复用户名称
        if (comment.getReplyToUserId() != null) {
            respVO.setReplyToUsername("用户" + comment.getReplyToUserId());
        }

        respVO.setCreateTime(comment.getCreateTime());

        // 查询回复列表
        if (comment.getParentId() == null) {
            List<PostCommentsDO> replies = postCommentsMapper.selectRepliesByParentId(comment.getCommentId());
            List<PostCommentRespVO> replyVOs = replies.stream()
                    .map(reply -> convertToRespVO(reply, userId))
                    .collect(Collectors.toList());
            respVO.setReplies(replyVOs);
        }

        // 查询是否已点赞
        if (userId != null) {
            PostLikesDO like = postLikesMapper.selectCommentLike(comment.getCommentId(), userId);
            respVO.setIsLiked(like != null && like.getStatus() == 1);
        } else {
            respVO.setIsLiked(false);
        }

        return respVO;
    }

}
